package com.huaxin.hxcloud.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.ArrangeUserDTO;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.SpacesItemDecoration;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author lwjing
 * @date 2018/3/24
 * @Desc $desc$
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxWorkFlowHandoutActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar      mToolbar;
    @BindView(R.id.rl_man)
    RecyclerView rl_man;
    @BindView(R.id.more)
    TextView     more;

    private View              emptyView;
    private HandOutManAdapter handOutManAdapter;
    private String            id;
    List<ArrangeUserDTO.ArrangeUser> userList = new ArrayList<>();
    private String taskId;
    //选择的人数
    private int count = 0;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_workflow_handout;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_ARRANGE_ID)) {
            id = extras.getString(Constants.IK_ARRANGE_ID);
            taskId = extras.getString(Constants.IK_TASK_ID);
        } else {
            finish();
        }
    }

    @Override
    public void initView() {
        setSupportActionBar(mToolbar);
        mToolbar.setTitle("任务分发");
        rl_man.setLayoutManager(new LinearLayoutManager(this));
        handOutManAdapter = new HandOutManAdapter(R.layout.item_handout_man, userList);
        rl_man.setAdapter(handOutManAdapter);
        rl_man.addItemDecoration(new SpacesItemDecoration(30));
        //空布局
        emptyView = LayoutInflater.from(this).inflate(R.layout.item_empty_nodata_center, (ViewGroup) rl_man.getParent(), false);

        handOutManAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if (view.getId() == R.id.cb_check) {
                    ArrangeUserDTO.ArrangeUser arrangeUser = userList.get(i);
                    CheckBox checkBox = (CheckBox) view;
                    if (checkBox.isChecked()) {
                        arrangeUser.setChecked(true);
                        count++;
                    } else {
                        arrangeUser.setChecked(false);
                        count--;
                    }
                    if (count > 0) {
                        more.setText("发送(" + count + ")");
                    } else {
                        more.setText("选择");
                    }
                    handOutManAdapter.setNewData(userList);
                }
            }
        });

        handOutManAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ArrangeUserDTO.ArrangeUser arrangeUser = userList.get(i);
                if (arrangeUser.isChecked()) {
                    arrangeUser.setChecked(false);
                    count--;
                } else {
                    arrangeUser.setChecked(true);
                    count++;
                }
                if (count > 0) {
                    more.setText("发送(" + count + ")");
                } else {
                    more.setText("选择");
                }
                handOutManAdapter.setNewData(userList);
            }
        });
    }

    @Override
    protected void requestData() {
        super.requestData();
        apiGetArrangeUser();
    }

    private void apiGetArrangeUser() {
        updateLoadStatus(LOADING);
        Call<ArrangeUserDTO> call = HxTransmitRequestHelper.getRequestApi().getArrangeUser(id);
        autoClose(call);
        Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<ArrangeUserDTO>() {
            @Override
            public void onResponse(Call<ArrangeUserDTO> call, Response<ArrangeUserDTO> response) {
                ArrangeUserDTO arrangeUserDTO = response.body();
                if (response.isSuccessful() && arrangeUserDTO != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    List<ArrangeUserDTO.ArrangeUser> users = arrangeUserDTO.getUserList();
                    Log.e("lwjing", "userList=" + users.size());
                    if (users != null && users.size() > 0) {
                        userList.addAll(users);
                        handOutManAdapter.setNewData(userList);
                    } else {
                        handOutManAdapter.setEmptyView(emptyView);
                    }
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<ArrangeUserDTO> call, Throwable t) {
                Log.d(TAG, "onFailure: ---->" + t);
                updateLoadStatus(LOAD_FAILURE);

            }
        });
    }

    /**
     * 提交分发
     */
    private void apiDistributeUser() {
        StringBuilder sb = new StringBuilder();
        for (ArrangeUserDTO.ArrangeUser arrangeUser : userList) {
            if (arrangeUser.isChecked()) {
                sb.append(arrangeUser.getUserId());
                sb.append(",");
            }
        }
        if (sb.length() <= 0) {
            ToastUtil.showToast("请至少选择一个人");
            return;
        }
        sb.deleteCharAt(sb.length() - 1);
        Log.e("lwjing", "userids=" + sb.toString());

        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().getDistributeUser(id, taskId, sb.toString());
        autoClose(call);
        Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful()) {
                    if (baseDTO != null) {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                    finish();
                } else {
                    if (baseDTO != null) {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                Log.d(TAG, "onFailure: ---->" + t);
                ToastUtil.showToast("分发失败，请重新发送");
            }
        });
    }

    @OnClick(R.id.more)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more:
                //确认分发
                apiDistributeUser();
                break;
        }
    }


    class HandOutManAdapter extends BaseQuickAdapter<ArrangeUserDTO.ArrangeUser, BaseViewHolder> {

        public HandOutManAdapter(int layoutResId, @Nullable List<ArrangeUserDTO.ArrangeUser> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, ArrangeUserDTO.ArrangeUser arrangeUser) {
            CheckBox cb_check = baseViewHolder.getView(R.id.cb_check);
            Log.e("lwjing", "convert=" + arrangeUser.toString());
            TextView tv_man = baseViewHolder.getView(R.id.tv_man);
            AvatarImageView igicon = baseViewHolder.getView(R.id.select_member_item_icon);
            HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
            instance.setHeadImage(HxWorkFlowHandoutActivity.this, "", arrangeUser.getNickName(), igicon);
            tv_man.setText(arrangeUser.getNickName());
            if (arrangeUser.isChecked()) {
                cb_check.setChecked(true);
            } else {
                cb_check.setChecked(false);
            }
            cb_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                }
            });
            baseViewHolder.addOnClickListener(R.id.cb_check);
        }
    }
}
